﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Npgsql;

namespace SpectationClient.SQLCommandBuilder {
    public class SetCondition: AbstractCondition {
        public enum Op:byte{
            IN_INTERSECTION,
            IN_UNION
        }
        private bool is_true = true;
        private Op set_operator;
        private List<NpgsqlCommand> set_command_list;
        private String column;
        

        public SetCondition(String column, bool is_true, Op set_operator) {
            init( column,  is_true,  set_operator);
        }
        public SetCondition(String column, Op set_operator) {
            init(column, true, set_operator);
        }

        private void init(String column, bool is_true, Op set_operator){
            this.set_command_list = new List<NpgsqlCommand>();
            this.column = column;
            this.set_operator = set_operator;
            this.is_true = is_true;
        
        }

        public void Add(NpgsqlCommand set_command){
            if(set_command != null && set_command.CommandText.Trim().Length > 0) this.set_command_list.Add(set_command);
        }

        public override bool IsEmpty { get { return this.set_command_list.Count == 0; } }

        public override NpgsqlCommand getCmd() {
            return this.getCmd("setCondition");
        }
        public override NpgsqlCommand getCmd(String prefix) {
            NpgsqlCommand cmd = new NpgsqlCommand();
            String set_op_str = "";
            bool moreThanOneSet = this.set_command_list.Count > 1;
            switch(this.set_operator) {
                case Op.IN_INTERSECTION: set_op_str = "INTERSECT"; break;
                case Op.IN_UNION: set_op_str = "UNION"; break;
            }
            cmd.CommandText = String.Format("{0} {1} (",this.column, ((this.is_true) ? " IN " : "NOT IN"));
            if(moreThanOneSet) cmd.CommandText += "(";
            for(int i = 0; i<this.set_command_list.Count; i++){
                
                NpgsqlCommand subCmd = this.set_command_list[i];
                CommandBuilder.appendCmd(ref cmd, subCmd);
                if(i < this.set_command_list.Count - 1) {
                    cmd.CommandText += ") "+set_op_str+" (";
                } else {
                    cmd.CommandText += ")";
                }
            
            }
            if(moreThanOneSet) cmd.CommandText += ")";
            return cmd;
        }
    }
}
